import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { RUNTIME_CFG_ENUM } from '@CIF/Runtime/Global/variable';
import { login } from '@/api/app.js';
import { setLocalstorage, removeLocalStorage, getLocalstorage } from '@/utils/localstorage';

const useMainStore = defineStore('main', {
	state: () => {
		return {
			cifAppCfg: {
				appId: 'appId',
				appName: '',
				referenceComponent: [],
				componentTree: '',
				theme: {},
				mode: RUNTIME_CFG_ENUM.PRODUCTION_MODE,
				contextOptions: {},
				rendererCanvasSize: {}
			},
			componentLibrary: []
		};
	},
	getters: {},
	actions: {
		async loginFunction(loginForm) {
			try {
				const res = await login(loginForm);
				setLocalstorage('access_token', res.access_token);
				setLocalstorage('username', loginForm.username);

				Cookies.set('tenant_id', getLocalstorage('tenantId'), { expires: 1 });
				Cookies.set('ego-userinfo', res.id, { expires: 1 });
			} catch (err) {
				removeLocalStorage('access_token');
				Cookies.remove('tenant_id');
				Cookies.remove('ego-userinfo');
				throw err;
			}
		}
	}
});
export default useMainStore;
